package cn.buddha.jesj.thread.jmm;

import lombok.extern.slf4j.Slf4j;

/**
 * @author shihao
 * @description volatile test
 */
@Slf4j
public class VolatileTest {

    private boolean initFlag = false;
//    private volatile boolean initFlag = false;

    public static void main(String[] args) throws InterruptedException {
        VolatileTest volatileTest = new VolatileTest();
        Thread threadA = new Thread(volatileTest::refresh2, "threadA");
        Thread threadB = new Thread(volatileTest::load2, "threadB");

        threadB.start();
        Thread.sleep(2000);
        threadA.start();
    }

    public void refresh1() {
        this.initFlag = true;
        log.info("线程：{}:修改共享变量initFlag", Thread.currentThread().getName());
    }

    public void load1() {
        while (!initFlag) {
        }
        log.info("线程：{}:当前线程嗅探到initFlag的状态的改变", Thread.currentThread().getName());
    }

    public void refresh2() {
        this.initFlag = true;

        try {
            Thread.sleep(7000);
        } catch (InterruptedException ignored) {
        }

        log.info("线程：{}:修改共享变量initFlag", Thread.currentThread().getName());
    }

    public void load2() {
        if (initFlag) {
            log.info("1.1线程{}获取到initFlag为true", Thread.currentThread().getName());
        } else {
            log.info("1.2线程{}获取到initFlag为false", Thread.currentThread().getName());
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException ignored) {
        }

        if (initFlag) {
            log.info("2.1线程{}获取到initFlag为true", Thread.currentThread().getName());
        } else {
            log.info("2.2线程{}获取到initFlag为false", Thread.currentThread().getName());
        }
    }

}
